package com.lagou.mvc.servlet;

import com.lagou.mvc.anno.*;
import com.lagou.mvc.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyDipatcherServlet extends HttpServlet {

    private Properties properties = new Properties();
    private List<String> classNames = new ArrayList<>();

    // ioc容器
    private Map<String, Object> ioc = new HashMap<String, Object>();

    // handlerMapping
    //private Map<String, Method> handlerMapping = new HashMap<>(); // 存储url和Method之间的映射关系
    private List<Handler> handlerMapping = new ArrayList<>();

    /**
     * 初始化方法
     *
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        //step1:tomcat加载springmvc.xml
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");//读入web.xml中的初始化数据
        doLoadConfig(contextConfigLocation);
        //step2:扫描包、注解
        doScan(properties.getProperty("scanPackage"));

        //step3:IOC容器进行bean初始化
        doInstance();

        //step4:依赖注入(基于注解)
        doAutowired();

        //step5:构造HandlerMapping，建立url和method之间的关系（springmvc相关组件初始化）
        initHandlerMapping();

        System.out.println("MyDipatcherServlet初始化完成....");

        // 等待请求进入，处理请求

    }


    /**
     * 构造一个HandlerMapping处理器映射器最关键的环节
     * 目的：将url和method建立关联
     */
    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> aClass = entry.getValue().getClass();

            //没有MyController注解直接跳过该类
            if (!aClass.isAnnotationPresent(MyController.class)) {
                continue;
            }

            //有MyController注解获取注解上的路径信息
            String baseUrl = "";
            if (aClass.isAnnotationPresent(MyRequestMapping.class)) {
                MyRequestMapping classMappingAnno = aClass.getAnnotation(MyRequestMapping.class);
                baseUrl = classMappingAnno.value();
            }

            //有MySecurity注解获取注解上的路径信息
            List<String> securityUserList = new ArrayList<>();
            if (aClass.isAnnotationPresent(MySecurity.class)) {
                MySecurity securityAnno = aClass.getAnnotation(MySecurity.class);
                String[] securityUserInfo = securityAnno.value();
                for (String securityUser : securityUserInfo) {
                    securityUserList.add(securityUser);
                }
            } else {//无权限设置默认所有用户都可以访问
                securityUserList.add("all");
            }

            if (!baseUrl.isEmpty()) {
                Method[] methods = aClass.getMethods();
                for (Method method : methods) {
                    //方法上无MyRequestMapping不处理
                    if (!method.isAnnotationPresent(MyRequestMapping.class)) {
                        continue;
                    }
                    //有注解
                    MyRequestMapping methodMappingAnno = method.getAnnotation(MyRequestMapping.class);
                    String methodUrl = methodMappingAnno.value();
                    Handler handler = new Handler(entry.getValue(), method, Pattern.compile(baseUrl + methodUrl));

                    //有MySecurity注解获取注解上的路径信息
                    List<String> securityUserListByMethod = new ArrayList<>();
                    if (method.isAnnotationPresent(MySecurity.class)) {
                        MySecurity securityAnnoByMethod = method.getAnnotation(MySecurity.class);
                        String[] securityUserInfoByMethod = securityAnnoByMethod.value();
                        for (String securityUser : securityUserInfoByMethod) {
                            //如果MyController类上MySecurity注解为all或者 类与方法MySecurity的存在并集，则存储
                            if (securityUserList.contains("all") || securityUserList.contains(securityUser)) {
                                securityUserListByMethod.add(securityUser);
                            }
                        }
                    } else {//无权限设置默认所有用户都可以访问
                        securityUserListByMethod.add("all");
                    }
                    handler.setPermitUsername(securityUserListByMethod);

                    //获取方法参数个数
                    Parameter[] parameters = method.getParameters();
                    Integer[] integers = new Integer[parameters.length];
                    for (int j = 0; j < parameters.length; j++) {
                        Parameter parameter = parameters[j];
                        if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                            // 如果是request和response对象，那么参数名称写HttpServletRequest和HttpServletResponse
                            handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);
                        } else {
                            handler.getParamIndexMapping().put(parameter.getName(), j);  // <name,2>
                        }

                    }
                    // 建立url和method之间的映射关系（map缓存起来）
                    handlerMapping.add(handler);
                }
            }
        }
    }

    //实现依赖注入
    private void doAutowired() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {

            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                //标明注入
                if (!declaredField.isAnnotationPresent(MyAutowired.class)) {
                    continue;
                }
                MyAutowired autowired = declaredField.getAnnotation(MyAutowired.class);
                //注入对象beanId
                String beanName = autowired.value();
                if (beanName.trim().isEmpty()) {
                    // 没有配置具体的bean id，那就需要根据当前字段类型注入（接口注入）
                    beanName = declaredField.getType().getName();
                }

                //开启赋值
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    //实现bean初始化
    private void doInstance() {
        if (classNames.size() == 0) {
            return;
        }
        try {
            for (String className : classNames) {
                //通过反射
                Class<?> aClass = Class.forName(className);
                //isAnnotationPresent()如果指定类型的注释存在于此元素上,返回true
                if (aClass.isAnnotationPresent(MyController.class)) {
                    MyController annotation = aClass.getAnnotation(MyController.class);
                    String name = aClass.getSimpleName();
                    if (annotation.value().isEmpty()) {
                        ioc.put(lowerFirst(name), aClass.newInstance());
                    } else {
                        ioc.put(annotation.value(), aClass.newInstance());
                    }
                } else if (aClass.isAnnotationPresent(MyService.class)) {
                    MyService annotation = aClass.getAnnotation(MyService.class);
                    String name = aClass.getSimpleName();
                    if (annotation.value().isEmpty()) {
                        ioc.put(lowerFirst(name), aClass.newInstance());
                    } else {
                        ioc.put(annotation.value(), aClass.newInstance());
                    }
                    // service层往往是有接口的，面向接口开发，此时再以接口名为id，放入一份对象到ioc中，便于后期根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        ioc.put(anInterface.getName(), aClass.newInstance());
                    }
                } else {
                    continue;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

    }

    // 首字母小写方法
    public String lowerFirst(String str) {
        if (str == null || str.isEmpty()) {
            return "";
        }
        char[] chars = str.toCharArray();
        if ('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    /**
     * 扫描特定包下的class
     *
     * @param scanPackage
     */
    private void doScan(String scanPackage) {
        //获取当前资源的虚拟路径
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                + scanPackage.replaceAll("\\.", "/");
        /*scanPackage.replace("\\.", "/");
        scanPackage.replaceAll("\\.", "/");*/
        File file = new File(path);
        /*list()方法是返回某个目录下的所有文件和目录的文件名，返回的是String数组
        listFiles()方法是返回某个目录下所有文件和目录的绝对路径，返回的是File数组*/

        File[] files = file.listFiles();
        for (File eachFile : files) {
            if (eachFile.isDirectory()) {//如果是文件夹，扫描包
                doScan(scanPackage + "." + eachFile.getName());
            } else if (eachFile.getName().endsWith(".class")) {//如果是class,存储class的名字
                String className = scanPackage + "." + eachFile.getName().replace(".class", "");
                classNames.add(className);
            }
        }
    }

    /**
     * 根据指定properties资源文件,加载信息
     *
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }

        // 以下就是为了向参数数组中塞值，而且还得保证参数的顺序和方法中形参顺序一致
        Map<String, String[]> parameterMap = req.getParameterMap();

        //获取用户名
        if (!parameterMap.containsKey("username") || parameterMap.get("username").length == 0) {
            resp.getWriter().write("A user name is required in the URL");
            return;
        }
        String username = parameterMap.get("username")[0];
        if (!checkUserSecurity(handler, username)) {
            resp.getWriter().write("The user is not authorized");
            return;
        }


        // 参数绑定
        // 获取所有参数类型数组，这个数组的长度就是我们最后要传入的args数组的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();

        // 根据上述数组长度创建一个新的数组（参数数组，是要传入反射调用的）
        Object[] paraValues = new Object[parameterTypes.length];


        // 遍历request中所有参数  （填充除了request，response之外的参数）
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            // name=1&name=2   name [1,2]
            String value = StringUtils.join(param.getValue(), ",");  // 如同 1,2

            // 如果参数和方法中的参数匹配上了，填充数据
            if (!handler.getParamIndexMapping().containsKey(param.getKey())) {
                continue;
            }

            // 方法形参确实有该参数，找到它的索引位置，对应的把参数值放入paraValues
            Integer index = handler.getParamIndexMapping().get(param.getKey());//name在第 2 个位置

            paraValues[index] = value;  // 把前台传递过来的参数值填充到对应的位置去

        }

        int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName()); // 0
        paraValues[requestIndex] = req;

        int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName()); // 1
        paraValues[responseIndex] = resp;

        // 最终调用handler的method属性
        try {
            Object invoke = handler.getMethod().invoke(handler.getController(), paraValues);
            //输出到页面
            resp.getWriter().write("state:success,the return data is :" + (invoke == null ? "null" : ""+invoke));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 权限校验
     *
     * @param handler
     * @param username
     * @return
     */
    private boolean checkUserSecurity(Handler handler, String username) {
        List<String> permitUsername = handler.getPermitUsername();
        System.out.println("可以访问（" + handler.getPattern() + "）路径的用户为：" + String.join(",", permitUsername));
        //如果该方法没有定义MySecurity注解，默认全部用户都可以访问
        if (permitUsername.contains("all")) {
            return true;
        }

        //如果可以访问的用户数目为0 或者 本次访问的用户名不在可访问列表中，则不予访问并返回提示信息
        if (permitUsername.size() == 0 || !permitUsername.contains(username)) {
            return false;
        }
        return true;
    }


    /**
     * 从request中获取Handler信息(通过url匹配)
     *
     * @param req
     * @return
     */
    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) {
            return null;
        }

        String url = req.getRequestURI();

        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }

        return null;

    }


}
